package nccloud.riart.pub.utils;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

import nc.bs.framework.common.RuntimeEnv;
import nc.bs.logging.Logger;
import nccloud.sso.dto.SSOParamDTO;
import nccloud.utils.mobile_riart.MessageLogger;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OAHttpClientUtils {

	public final static String URI = "/service/genThirdPartyAccessToken";
	
	public final static String URL_PREFIX = "http://";
	
	public final static String COLON = ":";//冒号
	
	public final static String CONTENT_TYPE = "application/x-www-form-urlencoded";
	
	public final static String CONTENT_LENGTH = "10000";
	
	public final static String REQUEST_METHOD = "POST";
	
	public final static String REQUEST_METHOD_GET = "GET";
	
	public final static String FILE_PATH = "resources/sso.properties";
	
	/**
	 * 请求OA,发送代办任务
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static String reqOA_Task(String urltype,String postdata) throws Exception {
		String strurl = OAUrlUtils.initUrl(urltype);
		OkHttpClient client = new OkHttpClient().newBuilder().build();
		MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
		RequestBody body = RequestBody.create(mediaType,postdata);
		Request request = new Request.Builder().url(strurl).method("POST", body)
		    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").build();
		try {
			Response response = client.newCall(request).execute();
			return response.body().string();
		} catch (IOException e) {
			MessageLogger.info("(请求OA,发送代办任务)reqOA_Task方法 【nccloud.riart.pub.utils.OAHttpClientUtils,错误描述：【"+e.getMessage()+"】");
			Logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return null; 
		
//		return "{\"result\":\"success\"}";
//		String strurl = OAUrlUtils.initUrl(urltype);
//		URL url = new URL(strurl + postdata);
//		HttpURLConnection hc = openConnectionPost(url);
//		OutputStream os = null;
//        DataOutputStream dos = null; 
//        String ret = "";
//        InputStream is = null;
//        try {
//        	
//        	hc.connect(); 
////        	os = hc.getOutputStream();
////        	dos = new DataOutputStream(os);
////        	dos.write(postdata.getBytes("UTF-8"));
////        	dos.flush();  
//        	
//        	if(hc.getResponseCode()==200) {
//	        	is = hc.getInputStream();
//	        	int ch;
//	        	while ((ch = is.read()) != -1) {
//	        		ret += String.valueOf((char) ch);
//	        	}
//        	}
//        }catch(Exception e) {
//        	Logger.error(e.getMessage(), e);
//        	ExceptionUtils.wrapException(e.getMessage(), e);
//        } finally {
//            if (dos != null) {
//                try {
//                    dos.close();
//                } catch (Exception e2) {
//                	Logger.error(e2.getMessage(), e2);
//                }
//            }
//            if (os != null) {
//                try {
//                    os.close();
//                } catch (Exception e2) {
//                	Logger.error(e2.getMessage(), e2);
//                }
//            }
//            if (is != null)
//                try {
//                    is.close();
//                } catch (Exception e2) {
//            }
//            if(hc!=null) {
//            	 try {
//            		 hc.disconnect();
//                 } catch (Exception e2) {
//                 }
//            }
//        }
//        return ret;
	}
	
	
	/**
	 * 请求OA,发送代办任务
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static String reqWX_Token() throws Exception {
		Properties wxProperties= OAUrlUtils.getWXUrlInfo();
		String wxIP = wxProperties.getProperty("wxIP");
		String wxPort = wxProperties.getProperty("wxPort");
		String CorpID = wxProperties.getProperty("CorpID");
		String Secret = wxProperties.getProperty("Secret");
		
		String strurl = "http://" + wxIP + ":" + wxPort + "/cgi-bin/gettoken?corpid="+ CorpID + "&corpsecret=" + Secret;
		URL url = new URL(strurl);
		HttpURLConnection hc = openConnectionGet(url);
        String ret = "";
        InputStream is = null;
        try {
        	hc.connect();
        	if(hc.getResponseCode()==200) {
	        	is = hc.getInputStream();
	        	int ch;
	        	while ((ch = is.read()) != -1) {
	        		ret += String.valueOf((char) ch);
	        	}
        	}
        }catch(Exception e) {
        	Logger.error(e.getMessage(), e);
        	e.printStackTrace();
        } finally {
            if (is != null)
                try {
                    is.close();
                } catch (Exception e2) {
            }
            if(hc!=null) {
           	 try {
           		 hc.disconnect();
                } catch (Exception e2) {
                }
           }
        }
        return ret;
	}
	
	/**
	 * 请求WX,发送代办任务
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static String reqWX_Message(String postdata,String access_token) throws Exception {
		Properties wxProperties= OAUrlUtils.getWXUrlInfo();
		String wxIP = wxProperties.getProperty("wxIP");
		String wxPort = wxProperties.getProperty("wxPort");

		String strurl = "http://" + wxIP + ":" + wxPort + "/cgi-bin/message/send?access_token="+ access_token;
		
		URL url = new URL(strurl);
		HttpURLConnection hc = openConnectionPost(url);
		OutputStream os = null;
        DataOutputStream dos = null;
        String ret = "";
        InputStream is = null;
        try {
        	os = hc.getOutputStream();
        	dos = new DataOutputStream(os);
        	dos.write(postdata.getBytes("UTF-8"));
        	dos.flush();
        	
        	if(hc.getResponseCode()==200) {
	        	is = hc.getInputStream();
	        	int ch;
	        	while ((ch = is.read()) != -1) {
	        		ret += String.valueOf((char) ch);
	        	}
        	}
        }catch(Exception e) {
        	Logger.error(e.getMessage(), e);
        	e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (Exception e2) {
                	Logger.error(e2.getMessage(), e2);
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e2) {
                	Logger.error(e2.getMessage(), e2);
                }
            }
            if (is != null)
                try {
                    is.close();
                } catch (Exception e2) {
            }
        }
        return ret;
	}
	
	/**
	 * 请求WX,撤回代办任务
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static String reqWX_Revoke(String postdata,String access_token) throws Exception {
		Properties wxProperties= OAUrlUtils.getWXUrlInfo();
		String wxIP = wxProperties.getProperty("wxIP");
		String wxPort = wxProperties.getProperty("wxPort");

		String strurl = "http://" + wxIP + ":" + wxPort + "/cgi-bin/message/revoke?access_token="+ access_token;
		
		URL url = new URL(strurl);
		HttpURLConnection hc = openConnectionPost(url);
		OutputStream os = null;
        DataOutputStream dos = null;
        String ret = "";
        InputStream is = null;
        try {
        	os = hc.getOutputStream();
        	dos = new DataOutputStream(os);
        	dos.write(postdata.getBytes("UTF-8"));
        	dos.flush();
        	
        	if(hc.getResponseCode()==200) {
	        	is = hc.getInputStream();
	        	int ch;
	        	while ((ch = is.read()) != -1) {
	        		ret += String.valueOf((char) ch);
	        	}
        	}
        }catch(Exception e) {
        	Logger.error(e.getMessage(), e);
        	e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (Exception e2) {
                	Logger.error(e2.getMessage(), e2);
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e2) {
                	Logger.error(e2.getMessage(), e2);
                }
            }
            if (is != null)
                try {
                    is.close();
                } catch (Exception e2) {
            }
        }
        return ret;
	}
	
	/**
	 * 打开URL链接
	 * @param url
	 * @return
	 * @throws IOException
	 */
	private static HttpURLConnection openConnectionPost(URL url) throws IOException {
		if(url == null) {
			throw new IOException("创建URL对象失败！");
		}
		URLConnection uc = url.openConnection();
		uc.setDoOutput(true);
		uc.setUseCaches(false);
		uc.setConnectTimeout(60000);
		uc.setRequestProperty("Content-Type",CONTENT_TYPE);
		uc.setRequestProperty("Content-Length", CONTENT_LENGTH);
		uc.setRequestProperty("charset", "UTF-8");
		HttpURLConnection hc = (HttpURLConnection) uc;
		hc.setRequestMethod(REQUEST_METHOD);
		return hc;
	}
	
	/**
	 * 打开URL链接
	 * @param url
	 * @return
	 * @throws IOException
	 */
	private static HttpURLConnection openConnectionGet(URL url) throws IOException {
		if(url == null) {
			throw new IOException("创建URL对象失败！");
		}
		URLConnection uc = url.openConnection();
		uc.setDoOutput(true); 
		uc.setUseCaches(false);
		uc.setConnectTimeout(60000);
		uc.setRequestProperty("Content-Type",CONTENT_TYPE);
		uc.setRequestProperty("Content-Length", CONTENT_LENGTH);
		uc.setRequestProperty("charset", "UTF-8");
		HttpURLConnection hc = (HttpURLConnection) uc;
		hc.setRequestMethod(REQUEST_METHOD_GET);
		return hc; 
	}
	
	public static SSOParamDTO loadSysParam(SSOParamDTO param) throws FileNotFoundException, IOException {
		Properties properties = getNCHomeProperties();
		param.setDatasource(properties.getProperty("datasource"));
		param.setThirdsys_client_id(properties.getProperty("thirdsys_client_id"));
		param.setThirdsys_client_security(properties.getProperty("thirdsys_client_security"));
		param.setReq_token_address(properties.getProperty("req_token_address"));
		param.setBusicentercode(properties.getProperty("busicentercode"));
		param.setIp(properties.getProperty("ip"));
		param.setPort(Integer.parseInt(properties.getProperty("port")));
		
		return param;
	}
	
	/**
	 * 获得注册在home中的properties文件
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static Properties getNCHomeProperties() throws FileNotFoundException, IOException {
		Properties properties = new Properties();
		FileInputStream inputStream = new FileInputStream(getRealPath());  //注意路径
		properties.load(inputStream);
		return properties;
	}
	
	/**
	 * 获得真实路径
	 * @return
	 */
	private static String getRealPath() {
		String homePath = RuntimeEnv.getInstance().getNCHome();
		homePath=homePath.replace("\\", "/");
		if(!homePath.endsWith("/")) {
			homePath += "/";
		}
		return homePath+FILE_PATH;
	}
	
	/** 
	 * 获取异常的堆栈信息 
	 *  
	 * @param t 
	 * @return 
	 */  
	private static String getStackTrace(Throwable t)  {  
	    StringWriter sw = new StringWriter();  
	    PrintWriter pw = new PrintWriter(sw);  
	  
	    try{  
	        t.printStackTrace(pw);  
	        return sw.toString();  
	    }finally{  
	        pw.close();  
	    }  
	} 
}
